import { useLocalSearchParams, useRouter, type Href } from 'expo-router';
import { useMemo, useState } from 'react';
import {
  KeyboardAvoidingView,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import Ionicons from '@expo/vector-icons/Ionicons';

import { MERCHANT_PASSWORD, MERCHANT_USERNAME } from '@/constants/config';
import { useAuth } from '@/context/auth-context';
import { encodeRedirectParam, normalizeRedirectParam, type RedirectTarget } from '@/utils/redirect';

type Channel = 'customer' | 'merchant';

const palette = {
  background: '#fff7fb',
  card: '#ffffff',
  accent: '#ff8fb1',
  accentDeep: '#ff6a9b',
  textPrimary: '#2f1f2b',
  textMuted: '#6a566a',
  tabInactive: 'rgba(255, 143, 177, 0.16)',
  inputBackground: '#fff8fb',
  inputBorder: '#f2cfe0',
  danger: '#d64f7c',
};

const CHANNEL_TABS: { label: string; value: Channel }[] = [
  { label: '个人账号', value: 'customer' },
  { label: '商户账号', value: 'merchant' },
];

export default function LoginScreen() {
  const router = useRouter();
  const params = useLocalSearchParams<{ redirect?: string; channel?: string }>();
  const { signIn } = useAuth();

  const sanitizedRedirect: RedirectTarget | undefined = useMemo(
    () => normalizeRedirectParam(params.redirect),
    [params.redirect],
  );

  const [channel, setChannel] = useState<Channel>(params.channel === 'merchant' ? 'merchant' : 'customer');
  const [customerPhone, setCustomerPhone] = useState('');
  const [customerPassword, setCustomerPassword] = useState('');
  const [merchantUsername, setMerchantUsername] = useState(MERCHANT_USERNAME);
  const [merchantPassword, setMerchantPassword] = useState(MERCHANT_PASSWORD);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setSubmitting] = useState(false);

  const isMerchant = channel === 'merchant';

  const handleChannelChange = (next: Channel) => {
    setChannel(next);
    setError(null);

    if (next === 'merchant') {
      if (!merchantUsername) {
        setMerchantUsername(MERCHANT_USERNAME);
      }
      if (!merchantPassword) {
        setMerchantPassword(MERCHANT_PASSWORD);
      }
    }
  };

  const handleSubmit = async () => {
    const normalizedPhone = customerPhone.replace(/\D/g, '');
    const credential = isMerchant ? merchantUsername.trim() : normalizedPhone;
    const rawPassword = isMerchant ? merchantPassword : customerPassword;
    const passwordToSend = rawPassword.trim();

    if (!isMerchant && credential.length !== 11) {
      setError('手机号需为 11 位数字');
      return;
    }

    if (isMerchant && credential.length === 0) {
      setError('请输入商户用户名');
      return;
    }

    if (!passwordToSend) {
      setError(isMerchant ? '请输入商户密码' : '请输入密码');
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      const signedInUser = await signIn({ credential, password: passwordToSend, channel });
      if (sanitizedRedirect) {
        router.replace(sanitizedRedirect as Href);
      } else {
        const fallback =
          signedInUser.channel === 'merchant' ? '/(merchant)/overview' : '/(tabs)';
        router.replace(fallback as Href);
      }
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message);
      } else {
        setError('登录失败，请稍后重试');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const redirectToRegister = () => {
    const redirectParam = sanitizedRedirect
      ? { redirect: encodeRedirectParam(sanitizedRedirect) }
      : undefined;
    router.replace({ pathname: '/(auth)/register', params: redirectParam });
  };

  const handleGoBack = () => {
    if (typeof router.canGoBack === 'function' && router.canGoBack()) {
      router.back();
    } else {
      router.replace('/(tabs)' as Href);
    }
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <ScrollView
          contentContainerStyle={styles.container}
          showsVerticalScrollIndicator={false}
          bounces={false}
        >
          <Pressable
            style={({ pressed }) => [
              styles.backButton,
              pressed && styles.backButtonPressed,
            ]}
            accessibilityRole="button"
            accessibilityLabel="返回上一页面"
            hitSlop={8}
            onPress={handleGoBack}
          >
            <Ionicons name="chevron-back" size={20} color={palette.textPrimary} />
            <Text style={styles.backButtonLabel}>返回</Text>
          </Pressable>

          <View style={styles.header}>
            <Text style={styles.title}>登录 PhotoSales+</Text>
            <Text style={styles.subtitle}>进入个人写真实验室，管理订单与相册内容</Text>
          </View>

          <View style={styles.card}>
            <View style={styles.tabs}>
              {CHANNEL_TABS.map((tab) => {
                const active = tab.value === channel;
                return (
                  <Pressable
                    key={tab.value}
                    style={[styles.tabItem, active && styles.tabItemActive]}
                    onPress={() => handleChannelChange(tab.value)}
                  >
                    <Text style={[styles.tabLabel, active && styles.tabLabelActive]}>
                      {tab.label}
                    </Text>
                  </Pressable>
                );
              })}
            </View>

            <View style={styles.formGroup}>
              <Text style={styles.inputLabel}>{isMerchant ? '用户名' : '手机号'}</Text>
              <TextInput
                value={isMerchant ? merchantUsername : customerPhone}
                onChangeText={(value) =>
                  isMerchant ? setMerchantUsername(value.trim()) : setCustomerPhone(value.replace(/\D/g, ''))
                }
                keyboardType={isMerchant ? 'default' : 'number-pad'}
                autoCapitalize="none"
                autoCorrect={false}
                maxLength={isMerchant ? undefined : 11}
                placeholder={isMerchant ? '请输入商户用户名' : '请输入 11 位手机号'}
                placeholderTextColor={palette.textMuted}
                style={styles.input}
                returnKeyType="next"
              />
            </View>

            <View style={styles.formGroup}>
              <Text style={styles.inputLabel}>{isMerchant ? '商户密码' : '密码'}</Text>
              <TextInput
                value={isMerchant ? merchantPassword : customerPassword}
                onChangeText={isMerchant ? setMerchantPassword : setCustomerPassword}
                secureTextEntry
                autoCapitalize="none"
                autoCorrect={false}
                placeholder={isMerchant ? '请输入商户密码' : '请输入登录密码'}
                placeholderTextColor={palette.textMuted}
                style={styles.input}
                returnKeyType="done"
              />
            </View>

            {isMerchant ? (
              <View style={styles.notice}>
                <Text style={styles.noticeTitle}>商户登录说明</Text>
                <Text style={styles.noticeText}>
                  商户账号信息由平台在配置文件中预先设置，请使用系统提供的用户名和密码登录。如需开通新的商户账号，请联系商务团队，我们将在 1 个工作日内回复。
                </Text>
              </View>
            ) : null}

            {error ? (
              <View style={styles.errorBadge}>
                <Text style={styles.errorText}>{error}</Text>
              </View>
            ) : null}

            <Pressable
              style={({ pressed }) => [
                styles.submitButton,
                pressed && styles.submitButtonPressed,
                isSubmitting && styles.submitButtonDisabled,
              ]}
              onPress={handleSubmit}
              disabled={isSubmitting}
            >
              <Text style={styles.submitText}>{isSubmitting ? '登录中...' : '立即登录'}</Text>
            </Pressable>

            {!isMerchant ? (
              <View style={styles.footer}>
                <Text style={styles.footerText}>还没有个人账号？</Text>
                <Pressable onPress={redirectToRegister}>
                  <Text style={styles.footerLink}>前往注册</Text>
                </Pressable>
              </View>
            ) : null}
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: palette.background,
  },
  flex: {
    flex: 1,
  },
  container: {
    alignItems: 'center',
    paddingHorizontal: 24,
    paddingVertical: 28,
    gap: 24,
  },
  backButton: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 14,
    backgroundColor: 'rgba(255,143,177,0.12)',
  },
  backButtonPressed: {
    backgroundColor: 'rgba(255,143,177,0.22)',
  },
  backButtonLabel: {
    fontSize: 13,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  header: {
    width: '100%',
    maxWidth: 520,
    gap: 8,
  },
  title: {
    fontSize: 28,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  subtitle: {
    fontSize: 14,
    color: palette.textMuted,
    lineHeight: 20,
  },
  card: {
    width: '100%',
    maxWidth: 520,
    borderRadius: 28,
    padding: 24,
    backgroundColor: palette.card,
    gap: 18,
    shadowColor: '#e2a7c1',
    shadowOpacity: 0.25,
    shadowOffset: { width: 0, height: 8 },
    shadowRadius: 20,
    elevation: 6,
  },
  tabs: {
    flexDirection: 'row',
    gap: 12,
    backgroundColor: palette.tabInactive,
    borderRadius: 20,
    padding: 6,
  },
  tabItem: {
    flex: 1,
    borderRadius: 16,
    paddingVertical: 10,
    alignItems: 'center',
  },
  tabItemActive: {
    backgroundColor: palette.accent,
  },
  tabLabel: {
    fontSize: 13,
    color: palette.textMuted,
    fontWeight: '600',
  },
  tabLabelActive: {
    color: palette.textPrimary,
  },
  formGroup: {
    gap: 8,
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  input: {
    height: 52,
    borderRadius: 16,
    paddingHorizontal: 16,
    backgroundColor: palette.inputBackground,
    borderWidth: 1,
    borderColor: palette.inputBorder,
    fontSize: 15,
    color: palette.textPrimary,
  },
  notice: {
    gap: 6,
    borderRadius: 18,
    backgroundColor: 'rgba(255,143,177,0.12)',
    padding: 16,
  },
  noticeTitle: {
    fontSize: 13,
    fontWeight: '600',
    color: palette.accentDeep,
  },
  noticeText: {
    fontSize: 12,
    color: palette.textMuted,
    lineHeight: 18,
  },
  errorBadge: {
    borderRadius: 12,
    backgroundColor: 'rgba(214,79,124,0.12)',
    borderWidth: 1,
    borderColor: 'rgba(214,79,124,0.24)',
    paddingHorizontal: 14,
    paddingVertical: 10,
  },
  errorText: {
    color: palette.danger,
    fontSize: 13,
  },
  submitButton: {
    borderRadius: 18,
    paddingVertical: 14,
    alignItems: 'center',
    backgroundColor: palette.accent,
  },
  submitButtonPressed: {
    backgroundColor: palette.accentDeep,
  },
  submitButtonDisabled: {
    opacity: 0.65,
  },
  submitText: {
    color: palette.textPrimary,
    fontSize: 16,
    fontWeight: '700',
    letterSpacing: 0.3,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 6,
  },
  footerText: {
    fontSize: 13,
    color: palette.textMuted,
  },
  footerLink: {
    fontSize: 13,
    color: palette.accentDeep,
    fontWeight: '700',
  },
});
